package com.ewhale.feitengguest.utils;

import android.content.Context;

import com.qiniu.android.common.FixedZone;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.Recorder;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.simga.library.http.Event;
import com.simga.library.http.HttpHelper;
import com.simga.library.http.Request;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import retrofit2.http.POST;

public class QiniuUtils {

    public static QiniuUtils instance = new QiniuUtils();
    public static UploadManager uploadManager;
    private static int picNum = 0;
    private static List<String> urls;

    public synchronized static QiniuUtils getInstance() {
        return instance;
    }

    public static void init() {
        Recorder recorder = new Recorder() {
            @Override
            public void set(String s, byte[] bytes) {
            }

            @Override
            public byte[] get(String s) {
                return new byte[0];
            }

            @Override
            public void del(String s) {
            }
        };

        Configuration config = new Configuration.Builder()
                .chunkSize(512 * 1024)        // 分片上传时，每片的大小。 默认256K
                .putThreshhold(1024 * 1024)   // 启用分片上传阀值。默认512K
                .connectTimeout(10)           // 链接超时。默认10秒
                .useHttps(true)               // 是否使用https上传域名
                .responseTimeout(60)          // 服务器响应超时。默认60秒
                .recorder(recorder)           // recorder分片上传时，已上传片记录器。默认null
                .recorder(recorder, null)   // keyGen 分片上传时，生成标识符，用于片记录器区分是那个文件的上传记录
                .zone(FixedZone.zone0)        // 设置区域，指定不同区域的上传域名、备用域名、备用IP。
                .build();
        uploadManager = new UploadManager(config);
    }

    public static void uploadImage(List<String> paths, onUploadImageCallBack callBack) {
        picNum = 0;
        new Request() {
            @Override
            public <T> void onNext(int postCode, T result, Object data) {
                super.onNext(postCode, result, data);
                if (postCode == 1) {
                    TokenDto dto = (TokenDto) result;
                    urls = new ArrayList<>();
                    upImage(dto, paths, callBack);
                }
            }

            @Override
            public void onError(int postCode, Object data, Throwable e) {
                super.onError(postCode, data, e);
            }
        }.request(1, HttpHelper.apiHttp.getService(QiniuApi.class).getToken(), null, Event.DESTROY);
    }


    private static void upImage(final TokenDto dto, final List<String> paths, final onUploadImageCallBack callBack) {
        if (picNum == paths.size()) {
            callBack.onResult(urls);
            return;
        }
        File file = new File(paths.get(picNum));
        if (!file.exists()) {//文件不存在
            picNum++;
            upImage(dto, paths, callBack);
            return;
        }
        String data = paths.get(picNum);
        String key = "ftzk" + System.currentTimeMillis() + ".jpg";
        String token = dto.token;
        uploadManager.put(data, key, token,
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject res) {
                        if (info.isOK()) {
                            try {
                                urls.add(dto.url.concat(res.getString("key")));
                                picNum++;
                                upImage(dto, paths, callBack);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }, null);
    }

    interface QiniuApi {
        @POST("app/common/getQiNiuTokenAndUrl.json")
        Observable<TokenDto> getToken();
    }

    public static class TokenDto {
        public String url;
        public String token;
    }

    public onUploadImageCallBack mCallBack;

    public void setCallBack(onUploadImageCallBack callBack) {
        mCallBack = callBack;
    }

    public interface onUploadImageCallBack {
        void onResult(List<String> keys);
    }
}
